<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>用户管理</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<link rel="stylesheet" href="${pageContext.request.contextPath }/assets/css/layui.css"  media="all">
	<link rel="stylesheet" href="${pageContext.request.contextPath }/assets/css/toastr.min.css"  media="all">
</head>
<body>
	<div class="demoTable" style="padding:10px 0 0 15px">
    	<div class="layui-inline">
        	<input class="layui-input" name="keyWord" id="keyWord" placeholder="请输入员工姓名" autocomplete="off">
    	</div> &nbsp; &nbsp; &nbsp; &nbsp;
    	<button class="layui-btn layui-btn-blue" style="margin: 0 0 0 10px" data-type="reload"><i class="layui-icon layui-icon-search">搜索</i></button>
	</div>
	
	
	<table class="layui-hide" id="test" lay-filter="test"></table>
<!-- 新增的表单 -->
<div id="formDiv" hidden>
	<form class="layui-form" id="addform">
		<br>
		<input type="hidden" id="uid" name="uid">
		<input lay-verify="status" class="layui-input" type="hidden" id="status" name="status" style="width:300px">
		<input lay-verify="password" class="layui-input" type="hidden" id="password" name="password" style="width:300px">
		<table>
			<tr>
				<td>&emsp;&emsp;&emsp;&emsp;工号&emsp;</td>
				<td><input lay-verify="account" class="layui-input" onfocus="editValue()" type="text" id="account" name="account" style="width:230px"></td>
				<td><font style="color:red; font-size: 24px;margin-left: 10px;">*</font></td>
				<td>&emsp;&emsp;&emsp;&emsp;部门名称&emsp;</td>
				<td>
					<select id="depName" name="depName" class="layui-input" lay-search="" lay-verify="depName">
						<option value="">请选择部门</option>
						<c:forEach items="${allDepartment }" var="dep">
							<option value="${dep.name}">${dep.name }</option>
						</c:forEach>
					</select>
				</td>
				<td><font style="color:red; font-size: 24px;margin-left: 10px;">*</font></td>
			</tr>
			<tr style="height:20px"></tr>
			<tr>
				<td>&emsp;&emsp;&emsp;&emsp;姓名&emsp;</td>
				<td><input lay-verify="userName" class="layui-input" type="text" id="userName" name="userName" style="width:230px"></td>
				<td><font style="color:red; font-size: 24px;margin-left: 10px;">*</font></td>
				<td>&emsp;&emsp;&emsp;&emsp;性别&emsp;</td>
				<td>
					<select id="six" name="six" class="layui-input" lay-search="" lay-verify="six" style="width:190px">
						<option value="">请选择性别</option>
						<option value="男">男</option>
						<option value="女">女</option>
					</select>
				</td>
				<td></td>
			</tr>
			<tr style="height:20px"></tr>
			<tr>
				<td>&emsp;&emsp;&emsp;&emsp;生日&emsp;</td>
				<td><input lay-verify="birthday" class="layui-input" type="text" id="birthday" name="birthday" style="width:230px"></td>
				<td></td>
				<td>&emsp;&emsp;&emsp;&emsp;联系方式&emsp;</td>
				<td><input  class="layui-input" type="text" id="phone" name="phone" style="width:230px"></td>
				<td></td>
			</tr>
			<tr style="height:20px"></tr>
			<tr>
				<td>&emsp;&emsp;&emsp;&emsp;qq&emsp;</td>
				<td><input lay-verify="qq" class="layui-input" type="text" id="qq" name="qq" style="width:230px"></td>
				<td></td>
				<td>&emsp;&emsp;&emsp;&emsp;入职日期&emsp;</td>
				<td><input lay-verify="ecode" class="layui-input" type="text" id="ecode" name="ecode" style="width:230px"></td>
				<td></td>
			</tr>
			<tr style="height:20px"></tr>
			<tr>
				<td id="lizhi"></td>
				<td id="lizhi2"></td>
				<td></td>
				<td id="updatePassword"></td>
				<td id="updatePassword2"></td>
				<td></td>
			</tr>
			<tr style="height:20px"></tr>
			<tr>
				<td colspan="2">&emsp;&emsp;&emsp;&emsp;<button class="layui-btn layui-btn-blue" id="submit" lay-submit lay-filter="addform" style="margin-left:140px">提交</button></td>
				<td colspan="2">&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;<button type="reset" class="layui-btn layui-btn-primary">重置</button></td>
			</tr>
		</table>
	</form>
</div>
<!-- 授权的表单 -->
<div id="formDiv2" hidden>
	<form class="layui-form" id="accreditform">
		<input type="hidden" id="uid" name="uid">
		<div class="layui-form-item">
			<label class="layui-form-label">授予的角色</label>
			<div id="accreditList" style="width: 70%;float: right;"></div>
		</div>
		<div class="layui-form-item">
			<button class="layui-btn layui-btn-blue" lay-submit lay-filter="accreditform" style="margin-left: 150px">授予角色</button>
		</div>
	</form>
</div>
<script type="text/html" id="toolbarDemo">
	<div class="layui-btn-container">
		<button class="layui-btn layui-btn-blue" lay-event="add"><i class="layui-icon layui-icon-add-1">  新增</i></button>
		<button class="layui-btn layui-btn-blue" lay-event="delete"><i class="layui-icon layui-icon-delete">批量删除</i></button>
	</div>
</script>
 
<script type="text/html" id="barDemo">
	<a class="layui-btn layui-btn-xs" lay-event="accredit">授权</a> 
	<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
              
<script src="${pageContext.request.contextPath }/assets/layui.js" charset="utf-8"></script>
<script src="${pageContext.request.contextPath }/assets/layui.all.js"></script>
<script src="${pageContext.request.contextPath }/assets/js/jquery.min.js" charset="utf-8"></script>
<script src="${pageContext.request.contextPath }/assets/js/toastr.min.js" charset="utf-8"></script>

<script>
layui.use(['table','layer','upload','form'], function(){
	var laydate = layui.laydate;
	var table = layui.table;
	var layer = layui.layer;
    var form = layui.form;
	
	  //执行一个laydate实例
	laydate.render({
		elem: '#birthday', //生日
		type: 'date',
		change: function(value, date, endDate){
			console.log(value); //得到日期生成的值，如：2017-08-18
		    console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
		    console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
		 }
	});
	  
	laydate.render({
		elem: '#ecode', //入职日期
		type: 'date',
		ready: function(date){
			console.log(date); //得到初始的日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
		}
	});
	
	var $ = layui.jquery, active = {
			reload:function () {
				var userName = $("#keyWord").val();
				table.reload('contenttable',{
					method:'get',
					where:{userName: userName},
					page:{
						curr:1  //重新从第一页开始
					}
				}); 
			}
		}
	$('.layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
	table.render({
	    elem: '#test'
	    ,url:'${pageContext.request.contextPath }/userMana/listPageUser.do'
	    ,toolbar: '#toolbarDemo'
	    ,title: '用户管理'
	    ,id :'contenttable'
	    ,limits:[10,20,30]
	    ,cols: [[
	    	{type: 'checkbox', fixed: 'left'}
	    	,{field:'', title:'序号', sort: true, type:'numbers', width: 60}
	      	,{field:'account', title:'工号', width:100}
	      	,{field:'userName', title:'姓名', width:200}
	      	,{field:'six', title:'性别', width:60}
	      	,{field:'birthday', title:'生日', width:175}
	      	,{field:'phone', title:'联系方式', width:175}
	      	,{field:'qq', title:'qq', width:175}
	      	,{field:'depName', title:'部门名称', width:200}
	      	,{field:'ecode', title:'入职日期', width:175}
	      	,{field:'tname', title:'离职日期', width:175}
	      	,{field:'status', title:'状态', width:100}
	      	,{fixed: 'right', title:'操作',  width: 200, toolbar: '#barDemo'}
	    ]]
	    ,page: true
	});
  
	//头工具栏事件
	table.on('toolbar(test)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
	    switch(obj.event){
	    case 'add':
	    	$('#lizhi').html('');
	    	$('#lizhi2').html('');
	    	$('#updatePassword').html('');
	    	$('#updatePassword2').html('');
	    	layer.open({
					  type: 1 		//Page层类型
					  ,area: ['850px', '450px'] //宽  高
					  ,title: '新增'
					  ,shade: 0.1 	//遮罩透明度
					  ,shadeClose: true //点击遮罩关闭
					  ,maxmin: true //允许全屏最小化
					  ,anim: 1 		//0-6的动画形式，-1不开启
					  ,content: $('#formDiv')
					  ,success: function () {
						  document.getElementById("addform").reset();
						  $('#uid').val('');
					  }
					  ,end: function () {
						  var formDiv = document.getElementById('formDiv');
						  formDiv.style.display = '';
					  }
					});
	      	break;
	    	case 'delete':
	        	var data = checkStatus.data;
	        	var str = "";
	        	if(data.length==0){
	        		toastr.warning("请至少选择一条记录！");
	        	}
	        	for(var i=0;i<data.length;i++){
	        		str += data[i].uid;
	        		if(i != data.length-1){
	        			str += ",";
	        		}
	        	}
	        	$.ajax({
			    	type:'post',
			    	url:'${pageContext.request.contextPath }/userMana/deleteUserOfVerify.do',
			    	data:{"str":str},
			    	dataType : "json",
			    	success:function(data){
			    		if(data>-1){
			    			toastr.warning("该条数据正在使用中，请勿删除！");
			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
								//关闭模态框
								// 父页面刷新
								/* window.location.reload();   */
							},1000);
			    		}else{
			    			layer.confirm('确定删除吗？', function(index){
				        		$.ajax({
							    	type:'post',
							    	url:'${pageContext.request.contextPath }/userMana/deleteUser.do',
							    	data:{"str" : str},
							    	success:function(data){
							    		if(data>0){
							    			toastr.success("删除成功！");
							    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
												//关闭模态框
												// 父页面刷新
												window.location.reload();  
											},2000); 
							    		}else{
							    			toastr.error("删除失败！");
							    		}
							    	}
							    }); 
				        	});
						}
		    		}
		   	 	});
	      	break;
	      	case 'select':
	      		console.log(obj)
	      	break;
	    };
	});
  
	//监听行工具事件（删除，编辑）
	table.on('tool(test)', function(obj){
		var data = obj.data;
		var uid = obj.data.uid;
		if(obj.event === 'del'){
			$.ajax({
		    	type:'post',
		    	url:'${pageContext.request.contextPath }/userMana/deleteUserOfVerify.do',
		    	data:{"str":uid},
		    	dataType : "json",
		    	success:function(data){
		    		if(data>0){
		    			toastr.warning("该条数据正在使用中，请勿删除！");
		    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
							//关闭模态框
							// 父页面刷新
							/* window.location.reload();   */
						},1000);
		    		}else{
		    			layer.confirm('确定删除吗？', function(index){
		    			    var uid = obj.data.uid;
		    			    $.ajax({
		    			    	type:'post',
		    			    	url:'${pageContext.request.contextPath }/userMana/deleteUser.do',
		    			    	data:{"str":uid},
		    			    	dataType : "json",
		    			    	success:function(data){
		    			    		if(data>0){
		    			    			toastr.success("删除成功！");
		    			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
		    								//关闭模态框
		    								// 父页面刷新
		    								window.location.reload();  
		    							},2000);
		    			    		}else{
		    			    			toastr.error("删除失败！");
		    			    		}
		    			    	}
		    			    })
		    			    layer.close(index);
		    			});
		    		}
		    	}
		    })
		} else if(obj.event === 'edit'){
			$('#lizhi').html('&emsp;&emsp;&emsp;&emsp;离职日期&emsp;');
			$('#lizhi2').html('<input lay-verify="tname" class="layui-input" type="text" id="tname" name="tname" style="width:230px">');
			$('#updatePassword').html('&emsp;&emsp;&emsp;&emsp;设定初始密码&emsp;');
			$('#updatePassword2').html('<input class="layui-input" type="text" id="remark3" name="remark3" style="width:230px">');
			laydate.render({
				elem: '#tname', //离职日期
				type: 'date',
				ready: function(date){
					console.log(date); //得到初始的日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
				}
			});
			layer.open({
				  type: 1 		//Page层类型
				  ,area: ['850px', '450px'] //宽  高
				  ,title: '编辑'
				  ,shade: 0.1 	//遮罩透明度
				  ,maxmin: true //允许全屏最小化
				  ,anim: 1 		//0-6的动画形式，-1不开启
				  ,content: $('#formDiv')
				  ,success: function () {
					//回显表单数据
					for(var i=0;i<Object.entries(data).length;i++) {
						var id = '#' + Object.entries(data)[i][0];
						var text = Object.entries(data)[i][1];
						$(id).val(text);
					}
					form.render();
				  }	
				  ,end: function () {
				  	var formDiv = document.getElementById('formDiv');
				  	formDiv.style.display = '';
			  	  }
			});
		} else if(obj.event === 'accredit'){
			$("#accreditList").empty();
			var uid = obj.data.uid;
			$("#uid").val(uid);
			$.ajax({
				type:"post",
				url:"${pageContext.request.contextPath }/userMana/getRoleByUser.do",
				data:{'uid':uid},
				dataType:"json",
				success:function(data){
					console.log(data);
					var list = data[0];
					console.log(list);
					layer.open({
						  type: 1 		//Page层类型
						  ,area: ['400px', '700px'] //宽  高
						  ,title: '用户授权'
						  ,shade: 0.1 	//遮罩透明度
						  ,maxmin: true //允许全屏最小化
						  ,anim: 1 		//0-6的动画形式，-1不开启
						  ,content:$("#formDiv2") 
						  ,success: function (data) {
							  for (var i = 0; i < list.length; i++) {
								  if (list[i].checked) {
									  $("#accreditList").append('<div class="layui-form-item" pane=""><input type="checkbox" lay-skin="primary"'+
												' name="rids" title="'+list[i].name+'" value="'+list[i].rid+'" checked=true><br></div>');
								} else {
									$("#accreditList").append('<div class="layui-form-item" pane=""><input type="checkbox" lay-skin="primary"'+
											' name="rids" title="'+list[i].name+'" value="'+list[i].rid+'"><br></div>');
								}
							}
							 form.render();
						  }
						,end: function () {
						  	var formDiv = document.getElementById('formDiv2');
						  	formDiv.style.display = '';
					  	  }
					});
				}
			});
		}
	});		
	
	
	/**
     * 表单校验
     */
    form.verify({
    	//value：表单的值、item：表单的DOM对象
    	 account: function(value){
    		 var str = value.replace(/\s+/g,"");
    		 if(str == ''){
    			return '工号不能为空';
    		}
    	},
    	userName: function(value){
    		var str = value.replace(/\s+/g,"");
    		if(str == ''){
    			return '员工姓名不能为空';
    		}
    	},
    	depName: function(value){
    		var str = value.replace(/\s+/g,"");
    		if(str == ''){
    			return '部门名称不能为空';
    		}
    	},
    });
    /**
     * 通用表单提交(AJAX方式)（新增）
     */
    form.on('submit(addform)', function (data) {
    	$("#submit").attr("disabled",true);
    	$.ajax({
   			url : '${pageContext.request.contextPath }/userMana/saveUser.do',
   			data : $('#addform').serialize(),
   			type : "post",
   			dataType : "json",
   			}).done(
   				function(res) {
   					if (res > 0) {
   						if(res == 2){
   							toastr.success('新增成功！');
   						}
   						if(res == 3){
   							toastr.success('修改成功！');
   						}
   						setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
   							//关闭模态框
   							// 父页面刷新
   							window.location.reload();  
   						},2000);
   					}else{
   						toastr.warning('工号重复！');
   					}
   				}
   			).fail(
   				function(res) {
   					if(res == -2){
   						toastr.error('新增失败！');
   					}
   					if(res == -3){
   						toastr.error('修改失败！');
   					}
   				}
   			)
		return false;
    });
    
    /**
     * 通用表单提交(AJAX方式)（授权）
     */
    form.on('submit(accreditform)', function (data) {
    	//alert($("#uid").val() + "test");
    	//获取多选框的值，合并为字符串
		var str = "";
		var arr=document.getElementsByName("rids");
		for(var i = 0; i < arr.length; i ++){
			if(arr[i].checked){
				var a = arr[i].value;
				str += a;
				str += ",";
			}
		}
		//去除字符串最后一位
		var rids = str.substring(0,str.length-1);
		var uid = $("#uid").val();
    	 $.ajax({
			url : '${pageContext.request.contextPath }/userMana/accreditUser.do',
			data : {"rids":rids, "uid":uid},
			type : "post",
			dataType : "json",
			}).done(
				function(res) {
					if (res > 0) {
						toastr.success('授权成功！');
						setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
							//关闭模态框
							// 父页面刷新
							window.location.reload();  
						},2000);
					}
				}
			).fail(
				function(res) {
					layer.close(1);
					toastr.error('授权失败！');
				}
			)
			return false; 
    });
});

function editValue(){
	$("#submit").attr("disabled",false);
}

toastr.options.positionClass = 'toast-top-center'; /* 提示框的位置设置为中上 */
</script>
</body>
</html>